package com.amkai.aes.webservice.binary.objecthandler.inventory;

import java.io.Serializable;

import org.hibernate.Query;

import com.amkai.aes.aescommon.factory.RADBeanFactory;
import com.amkai.aes.aescommon.service.binary.job.inventory.OrderRequisitionNumberJob;
import com.amkai.aes.aescommon.service.binary.job.inventory.RequisitionNumberData;
import com.amkai.aes.generatedbeans.inventory.purchasing.PurchaseNumber;
import com.amkai.aes.generatedbeans.inventory.purchasing.PurchaseOrder;
import com.amkai.aes.generatedbeans.inventory.requisitioning.OrderRequisition;
import com.amkai.aes.generatedbeans.inventory.requisitioning.OrderRequisitionNumber;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class RequisitionNumberHandler implements JobObjectHandler<OrderRequisitionNumberJob,Serializable, RequisitionNumberData> {
	private static final String reqquery = "select req from OrderRequisition req  where req.requisitionNumber = :num and req.baseOrganization.id = :depId";
	private static final String query = "select reqnum from OrderRequisitionNumber reqnum where  reqnum.baseOrganization.id = :depId";
	@Override
	public RequisitionNumberData process(OrderRequisitionNumberJob job,
			Serializable object) throws Exception {
		SessionManager sm = SiteManager.Start();
		OrderRequisitionNumber reqnum;
		if (!job.getNumdata().getNeedValidate()) { //nem validalni kell hanem uj number kell
			try {
				sm.openSession();
				Query q;
				q = sm.execute(query);
				q = q.setLong("depId", job.getModuleDepartment().getId());
				reqnum = (OrderRequisitionNumber) q.uniqueResult();
				if (reqnum == null) {
					 reqnum = RADBeanFactory.getInstance().createBean(OrderRequisitionNumber.class);
					 reqnum.setBaseOrganization(job.getModuleDepartment());
				}
				RequisitionNumberData result = new RequisitionNumberData();
				long num = reqnum.getNumber();
				num++;
				reqnum.setNumber(num);
				sm.saveRAD(reqnum);
				sm.commitTransaction();
				result.setRequisitionnumber(String.valueOf(num));
				return result;
			} catch (Exception e) {
				sm.rollbackTransaction();
				throw e;
			} finally {
				sm.closeSession();
			}
		}else{
			try {
				sm.openSession();
				Query q;
				q = sm.execute(reqquery);
				q = q.setLong("depId", job.getModuleDepartment().getId());
				q = q.setString("num", job.getNumdata().getRequisitionnumber());
				OrderRequisition req = (OrderRequisition)q.uniqueResult();
				RequisitionNumberData result = new RequisitionNumberData();
				result.setRequissitionvalid(req == null || req.getId().equals(job.numdata.getRequisitionId()));
				return result;
			} catch (Exception e) {
				throw e;
			} finally {
				sm.closeSession();
			}
				
		}
		
	}



}
